﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace P2P_Backup.connections
{
    public class UdpBroadcast
    {
        UdpClient udpClient;
        IPEndPoint endPoint;
        Thread udpBroadcaster;

        public UdpBroadcast(IPEndPoint endPoint)
        {
            this.endPoint = endPoint;
            udpClient = new UdpClient(endPoint);
            
            startUdpListener();
            Console.WriteLine("Started Listening for Peer anncouncments");

            udpBroadcaster = new Thread(broadcastUdp);
            udpBroadcaster.IsBackground = true;
            udpBroadcaster.Start();
        }
        private void startUdpListener()
        {
            udpClient.BeginReceive(new AsyncCallback(ReceiveUdp), endPoint);
        }
        private void ReceiveUdp(IAsyncResult ar)
        {
            IPEndPoint endPoint = (IPEndPoint)ar.AsyncState;

            byte[] bytes = udpClient.EndReceive(ar, ref endPoint);
            string[] data = tools.net.getDataFromBytes(bytes);
            if (data[0] == "ANC")
            {
                if (P2PBackup.Instance.Local.IpAddress.Equals(endPoint.Address))
                {
                    Console.WriteLine("Own Announcment recieved");
                }
                else
                {
                    RemotePeer peer = new RemotePeer(endPoint.Address, data[1]);
                    Console.WriteLine("Announcment recieved from: {0}", endPoint.Address);
                }
            }
            startUdpListener();
        }

        private void broadcastUdp()
        {
            IPEndPoint broadcast = new IPEndPoint(IPAddress.Broadcast, P2PBackup.ApplicationPort);
            string data = String.Format("ANC {0}", P2PBackup.Instance.Local.Hostname);
            byte[] bytes = tools.net.getBytes(data);

            UdpClient udpBroadcast = new UdpClient();
            udpBroadcast.Send(bytes, bytes.Length, broadcast);
            Console.WriteLine(String.Format("Announcment send on: {0}", broadcast));
        }

    }
}
